package com.share.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.share.common.error.BizException;
import com.share.common.error.JsonReturnCode;
import com.wechat.pay.java.core.util.PemUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.Base64Utils;

import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.SignatureException;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 百度人脸识别工具类
 */
@Slf4j
public class AuthUtil {


    public static void main(String[] args) {
        String path = "C:\\00openjaw\\00project\\other\\cherry\\bb.jpg";
        String out = "C:\\00openjaw\\00project\\other\\cherry\\cc.jpg";
//        bb(path);
//        rotate(path, out);
//        bb(out);

    }


    public static void bb(String path) {
        try {
            File imageFile = new File(path); // 替换为图片路径
            long size = imageFile.length() / 1024;
            BufferedImage image = ImageIO.read(imageFile);
            int width = image.getWidth();
            int height = image.getHeight();

            System.out.println("size: " + size);
            System.out.println("Width: " + width);
            System.out.println("Height: " + height);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 反转图像
     *
     * @param path
     * @param out
     */
    public static void rotate(String path, String out) {
        try {
            BufferedImage originalImage = ImageIO.read(new File(path));
            // 获取原始图像的宽高信息
            int width = originalImage.getWidth();
            int height = originalImage.getHeight();
            // 创建新的 BufferedImage 对象，大小为旋转后的图像尺寸
            BufferedImage rotatedImage = new BufferedImage(height, width, 6);
            // 获取 Graphics2D 上下文
            Graphics2D g2d = rotatedImage.createGraphics();
            // 设置旋转角度（逆时针）
            double radians = Math.PI / 2;
            // 执行旋转操作
            g2d.rotate(-radians);
            // 绘制原始图像到旋转后的位置
            g2d.drawImage(originalImage, -width, 0, null);
            // 清除 Graphics2D 上下文
            g2d.dispose();
            // 输出旋转后的图像
            File outputFile = new File(out);
            ImageIO.write(rotatedImage, FileUtil.getSuffix(path), outputFile);
        } catch (Exception e) {
            log.error("rotate:", e);
        }
    }


    public static void aa(String root) {

        List<File> fileList = FileUtil.getFileList(root);

        for (File file : fileList) {
            String text = getText(file.getAbsolutePath());
            System.out.println(text);
        }

    }



    /**
     * 获取图片文字
     *
     * @param imgPath 图片路径
     */
    public static String getText(String imgPath) {
        String base = FileUtil.imageToUrlEncode(imgPath);
        Map<String, String> header = new HashMap<>();
        header.put("Content-Type", "application/x-www-form-urlencoded");
        String param = "image=" + base;
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=" + getAuth();
        System.out.println(url);
        return HttpUtil.doPost(url, param, header);


    }

    /**
     * 人像对比
     *
     * @param imgPath 图片路径
     */
    public static void qrcode(String imgPath) {
        String base = FileUtil.imageToUrlEncode(imgPath);
        Map<String, String> header = new HashMap<>();
        header.put("Content-Type", "application/x-www-form-urlencoded");
        String param = "image=" + base;
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/waybill?access_token=" + getAuth();
        System.out.println(url);
        String s = HttpUtil.doPost(url, param, header);
        System.out.println(s);
    }

    /**
     * 获取微信支付证书
     *
     * @param signatureStr
     * @param privateKey
     * @return
     * @throws InvalidKeyException
     * @throws NoSuchAlgorithmException
     * @throws SignatureException
     */
    public static String getSign(String signatureStr, String privateKey) {
        try {
            //replace 根据实际情况，不一定都需要
            String replace = privateKey.replace("\\n", "\n");
            PrivateKey merchantPrivateKey = PemUtil.loadPrivateKeyFromPath(replace);
            Signature sign = Signature.getInstance("SHA256withRSA");
            sign.initSign(merchantPrivateKey);
            sign.update(signatureStr.getBytes(StandardCharsets.UTF_8));
            return Base64Utils.encodeToString(sign.sign());
        } catch (Exception e) {
            log.error("----getSign-----the err is", e);
            throw new BizException(JsonReturnCode.CREAT_ORDER_ERR);
        }
    }

    public static String decrypt(String key, String nonce, String associatedData, String ciphertext) throws Exception {
        byte[] keyBytes = key.getBytes();
        byte[] nonceBytes = nonce.getBytes();
        byte[] associatedDataBytes = associatedData.getBytes();
        byte[] ciphertextBytes = Base64.getDecoder().decode(ciphertext);

        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        Key secretKey = new SecretKeySpec(keyBytes, "AES");
        GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, nonceBytes);

        cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec);
        cipher.updateAAD(associatedDataBytes);

        byte[] decryptedBytes = cipher.doFinal(ciphertextBytes);
        return new String(decryptedBytes);
    }
    public static String getAuth() {
        String url = String.format(Constant.AUTH_URL, Constant.CLIENT_ID, Constant.CLIENT_SECRET);
        String result = HttpUtil.doGet(url);
        System.out.println(result);
        JSONObject parse = JSON.parseObject(result);
        return parse.getString("access_token");
    }

}